﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace MicroMVVM.Navigation
{
    /// <summary>
    /// This class contains the functions to serialize and deserialize objects.
    /// </summary>
    internal class Serializer
    {
        /// <summary>
        /// Deserialise a string to an object.
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        /// <param name="json">JSON string</param>
        /// <returns>Object</returns>
        public static T Deserialize<T>(string json)
        {
            var bytes = Encoding.Unicode.GetBytes(json);

            using (var stream = new MemoryStream(bytes))
            {
                var serializer = new DataContractJsonSerializer(typeof (T));

                return (T) serializer.ReadObject(stream);
            }
        }

        /// <summary>
        /// Serializes an object to a string.
        /// </summary>
        /// <param name="instance">Object instance</param>
        /// <returns>Serialized object</returns>
        public static string Serialize(object instance)
        {
            if (instance == null) return string.Empty;

            using (var stream = new MemoryStream())
            {
                var serializer = new DataContractJsonSerializer(instance.GetType());
                serializer.WriteObject(stream, instance);
                stream.Position = 0;

                using (var reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
}